import java.util.*;

public class CanFinish {

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        ArrayList<List<Integer>> edge = new ArrayList<>();
        int[] inDeg = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            edge.add(new ArrayList<>());
        }
        for (int[] prerequisite : prerequisites) {
            edge.get(prerequisite[1]).add(prerequisite[0]);
            ++inDeg[prerequisite[0]];
        }
        LinkedList<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (inDeg[i] == 0) queue.add(i);
        }
        int count = 0;
        while (!queue.isEmpty()) {
            ++count;
            Integer poll = queue.poll();
            for (Integer i : edge.get(poll)) {
                --inDeg[i];
                if (inDeg[i] == 0) queue.add(inDeg[i]);
            }
        }
        return count == numCourses;
    }
}
